/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jsibbold.zoomage;

import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;

/**
 * 回弹效果类
 *
 * @since 2021-05-31
 */
public class ReboundHelper implements AnimatorValue.ValueUpdateListener, Animator.StateChangedListener {
    private static final int DEFAULTDURATION = 100;

    private final ReboundListener mListener;

    private final AnimatorValue mAnimatorValue;

    private float mFromX;
    private float mFromY;
    private float mToX;
    private float mToY;

    /**
     * ReboundHelper
     *
     * @param listener listener
     */
    public ReboundHelper(ReboundListener listener) {
        mListener = listener;
        mAnimatorValue = new AnimatorValue();
        mAnimatorValue.setDuration(DEFAULTDURATION);
        mAnimatorValue.setCurveType(Animator.CurveType.ACCELERATE);
        mAnimatorValue.setValueUpdateListener(this);
        mAnimatorValue.setStateChangedListener(this);
    }

    /**
     * rebound
     *
     * @param fromX 当前坐标X
     * @param fromY 当前坐标Y
     * @param toX 改变到X
     * @param toY 改变到Y
     */
    public void rebound(float fromX, float fromY, float toX, float toY) {
        if (mAnimatorValue.isRunning()) {
            return;
        }
        mFromX = fromX;
        mFromY = fromY;
        mToX = toX;
        mToY = toY;
        mAnimatorValue.start();
    }

    @Override
    public void onUpdate(AnimatorValue animatorValue, float value) {
        float offsetX = mFromX + (mToX - mFromX) * value;
        float offsetY = mFromY + (mToY - mFromY) * value;
        mListener.update(offsetX, offsetY);
    }

    @Override
    public void onStart(Animator animator) {
    }

    @Override
    public void onStop(Animator animator) {
    }

    @Override
    public void onCancel(Animator animator) {
    }

    @Override
    public void onEnd(Animator animator) {
        mListener.update(mToX, mToY);
    }

    @Override
    public void onPause(Animator animator) {
    }

    @Override
    public void onResume(Animator animator) {
    }

    /**
     * 回弹效果类
     *
     * @since 2021-05-31
     */
    public interface ReboundListener {
        /**
         * update
         *
         * @param offsetX offsetX
         * @param offsetY offsetY
         */
        void update(float offsetX, float offsetY);
    }
}
